import logging
import json
from typing import Dict, Any
from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import JSONResponse
from app.services.shopify_product_import_service import shopify_product_import_service
from app.utils.error_handling import BadRequestError, InternalServerError

# 配置日志
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

# 创建FastAPI Router
router = APIRouter(prefix="/api/v1/shopify", tags=["Shopify Product Import"])


@router.post('/import-products')
async def import_products(request: Request) -> Dict[str, Any]:
    """
    导入商品数据到数据库的接口
    
    入参JSON格式：
    {
        "shopify_domain": "your-store.myshopify.com"  # Shopify店铺域名
    }
    
    返回格式：
    {
        "is_success": 1,  # 1表示成功，0表示失败
        "message": "Products imported successfully",
        "total": 100,  # 总商品数
        "inserted": 80,  # 新增数量
        "updated": 20   # 更新数量
    }
    """
    try:
        # 记录请求开始
        logger.info("接收到导入商品数据的请求")
        
        # 检查请求内容类型
        content_type = request.headers.get('Content-Type', '')
        if not content_type.startswith('application/json'):
            logger.warning(f"请求内容类型不是JSON: {content_type}")
            raise HTTPException(
                status_code=400,
                detail={
                    "is_success": 0,
                    "error": "Content-Type must be application/json"
                }
            )
        
        # 解析请求体
        try:
            data = await request.json()
        except json.JSONDecodeError:
            logger.warning("请求体JSON格式无效")
            raise HTTPException(
                status_code=400,
                detail={
                    "is_success": 0,
                    "error": "Invalid JSON format in request body"
                }
            )
        
        if not data:
            logger.warning("请求体为空")
            raise HTTPException(
                status_code=400,
                detail={
                    "is_success": 0,
                    "error": "Request body cannot be empty"
                }
            )
        
        # 验证必需参数
        shopify_domain = data.get("shopify_domain")
        if not shopify_domain:
            logger.warning("缺少必需参数: shopify_domain")
            raise HTTPException(
                status_code=400,
                detail={
                    "is_success": 0,
                    "error": "Missing required field: shopify_domain"
                }
            )
        
        # 验证参数类型
        if not isinstance(shopify_domain, str) or not shopify_domain.strip():
            raise HTTPException(
                status_code=400,
                detail={
                    "is_success": 0,
                    "error": "shopify_domain must be a non-empty string"
                }
            )
        
        # 记录参数信息
        logger.info(f"处理导入商品数据请求: shopify_domain={shopify_domain}")
        
        # 调用服务层处理导入
        result = shopify_product_import_service.import_products(shopify_domain)
        
        # 根据结果返回响应
        if result.get("is_success") == 1:
            logger.info(f"商品数据导入成功，店铺: {shopify_domain}, 总数: {result.get('total', 0)}")
            return result
        else:
            # 判断错误类型返回适当的状态码
            status_code = 400  # 默认为客户端错误
            error_info = result.get("error", "Unknown error")
            
            # 如果是系统内部错误，返回500
            if "Internal error" in str(error_info):
                status_code = 500
            
            logger.error(f"商品数据导入失败: {error_info}")
            raise HTTPException(
                status_code=status_code,
                detail=result
            )
            
    except BadRequestError as e:
        # 捕获业务逻辑错误
        logger.warning(f"业务逻辑错误: {str(e)}")
        raise HTTPException(
            status_code=400,
            detail={
                "is_success": 0,
                "error": str(e)
            }
        )
        
    except InternalServerError as e:
        # 捕获内部服务器错误
        logger.error(f"内部服务器错误: {str(e)}")
        raise HTTPException(
            status_code=500,
            detail={
                "is_success": 0,
                "error": str(e)
            }
        )
        
    except HTTPException:
        # 重新抛出HTTP异常
        raise
        
    except Exception as e:
        # 捕获其他未预期的错误
        logger.error(f"未预期的错误: {str(e)}", exc_info=True)
        return JSONResponse(
            status_code=500,
            content={
                "is_success": 0,
                "error": "Internal server error"
            }
        )


@router.post('/import-product-variants')
async def import_product_variants(request: Request) -> Dict[str, Any]:
    """
    导入商品变体数据到数据库的接口
    
    入参JSON格式：
    {
        "shopify_domain": "your-store.myshopify.com"  # Shopify店铺域名
    }
    
    返回格式：
    {
        "is_success": 1,  # 1表示成功，0表示失败
        "message": "Product variants imported successfully",
        "total": 200,  # 总变体数
        "inserted": 150,  # 新增数量
        "updated": 50    # 更新数量
    }
    """
    try:
        # 记录请求开始
        logger.info("接收到导入商品变体数据的请求")
        
        # 检查请求内容类型
        content_type = request.headers.get('Content-Type', '')
        if not content_type.startswith('application/json'):
            logger.warning(f"请求内容类型不是JSON: {content_type}")
            raise HTTPException(
                status_code=400,
                detail={
                    "is_success": 0,
                    "error": "Content-Type must be application/json"
                }
            )
        
        # 解析请求体
        try:
            data = await request.json()
        except json.JSONDecodeError:
            logger.warning("请求体JSON格式无效")
            raise HTTPException(
                status_code=400,
                detail={
                    "is_success": 0,
                    "error": "Invalid JSON format in request body"
                }
            )
        
        if not data:
            logger.warning("请求体为空")
            raise HTTPException(
                status_code=400,
                detail={
                    "is_success": 0,
                    "error": "Request body cannot be empty"
                }
            )
        
        # 验证必需参数
        shopify_domain = data.get("shopify_domain")
        if not shopify_domain:
            logger.warning("缺少必需参数: shopify_domain")
            raise HTTPException(
                status_code=400,
                detail={
                    "is_success": 0,
                    "error": "Missing required field: shopify_domain"
                }
            )
        
        # 验证参数类型
        if not isinstance(shopify_domain, str) or not shopify_domain.strip():
            raise HTTPException(
                status_code=400,
                detail={
                    "is_success": 0,
                    "error": "shopify_domain must be a non-empty string"
                }
            )
        
        # 记录参数信息
        logger.info(f"处理导入商品变体数据请求: shopify_domain={shopify_domain}")
        
        # 调用服务层处理导入
        result = shopify_product_import_service.import_product_variants(shopify_domain)
        
        # 根据结果返回响应
        if result.get("is_success") == 1:
            logger.info(f"商品变体数据导入成功，店铺: {shopify_domain}, 总数: {result.get('total', 0)}")
            return result
        else:
            # 判断错误类型返回适当的状态码
            status_code = 400  # 默认为客户端错误
            error_info = result.get("error", "Unknown error")
            
            # 如果是系统内部错误，返回500
            if "Internal error" in str(error_info):
                status_code = 500
            
            logger.error(f"商品变体数据导入失败: {error_info}")
            raise HTTPException(
                status_code=status_code,
                detail=result
            )
            
    except BadRequestError as e:
        # 捕获业务逻辑错误
        logger.warning(f"业务逻辑错误: {str(e)}")
        raise HTTPException(
            status_code=400,
            detail={
                "is_success": 0,
                "error": str(e)
            }
        )
        
    except InternalServerError as e:
        # 捕获内部服务器错误
        logger.error(f"内部服务器错误: {str(e)}")
        raise HTTPException(
            status_code=500,
            detail={
                "is_success": 0,
                "error": str(e)
            }
        )
        
    except HTTPException:
        # 重新抛出HTTP异常
        raise
        
    except Exception as e:
        # 捕获其他未预期的错误
        logger.error(f"未预期的错误: {str(e)}", exc_info=True)
        return JSONResponse(
            status_code=500,
            content={
                "is_success": 0,
                "error": "Internal server error"
            }
        )

